package ${domain}.frame.auth;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import ${domain}.frame.utils.PropertiesUtil;
import ${domain}.frame.utils.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * LocalData - 本地数据存放类
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
public class LocalData {

    private static String[] applicationArgs = null;

    private static ApplicationContext applicationContext = null;

    private static Token system = null;

    static {
        // 组装系统Token
        system = new Token();
        system.setId(0);
        system.setUserId(0);
        system.setUserName("system");
        system.putRes(".*");
    }

    public static Token getSysToken() {
        return system;
    }

    /**
     * 当前用户的通行证
     */
    private static final ThreadLocal<Token> tokenHolder = new ThreadLocal();

    public static Token getToken() {
        return tokenHolder.get();
    }

    public static void setToken(Token token) {
        tokenHolder.set(token);
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static ApplicationContext getApplicationContext() {
        return LocalData.applicationContext;
    }

    public static void init(ApplicationContext context, String[] args) {
        LocalData.applicationContext = context;
        LocalData.applicationArgs = args;
    }

    /**
     * 是否初始化完成
     *
     * @return 是否
     */
    public static boolean isInited() {
        return LocalData.applicationContext != null;
    }

    public static <T> T getBean(Class<T> t) {
        if (getApplicationContext() == null) {
            return null;
        }
        try {
            return getApplicationContext().getBean(t);
        } catch (BeansException ignored) {
            return null;
        }
    }

    public static Environment getEnvironment() {
        return getBean(Environment.class);
    }

    public static String getProperty(String key, String defaultValue) {
        Environment environment = getEnvironment();
        if (environment != null) {
            return environment.getProperty(key, defaultValue);
        } else {
            String active = LocalData.getActive();
            if (StringUtil.isEmpty(active)) {
                return PropertiesUtil.getProp("application.properties", key, defaultValue);
            } else {
                return PropertiesUtil.getProp("application-" + active + ".properties", key, defaultValue);
            }
        }
    }

    public static String getActive() {
        // 当上下文初始化已完成后优先使用SpringBoot内存参数
        Environment environment = getEnvironment();
        if (environment != null) {
            return environment.getProperty("spring.profiles.active", "");
        }

        String active = "";
        // 1命令行环境  --spring.profiles.active=dev
        if (applicationArgs != null) {
            Pattern compile = Pattern.compile("--spring\\.profiles\\.active=(.*)");
            for (String arg : applicationArgs) {
                Matcher matcher = compile.matcher(arg);
                if (matcher.find()) {
                    active = matcher.group(1);
                }
            }
            if (StringUtil.isNotEmpty(active)) {
                return active;
            }
        }

        // 2Java系统属性 -Dspring.profiles.active=dev
        active = System.getProperty("spring.profiles.active");
        if (StringUtil.isNotEmpty(active)) {
            return active;
        }

        // 3操作系统环境变量 SPRING_PROFILES_ACTIVE=dev
        active = System.getenv("SPRING_PROFILES_ACTIVE");
        if (StringUtil.isNotEmpty(active)) {
            return active;
        }

        // 4配置文件 spring.profiles.active=dev
        return PropertiesUtil.getProp("application.properties", "spring.profiles.active", "");
    }

    public static String getContext() {
        return getRequest().getContextPath();
    }
}